<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, RecommendItem } from '@/types/home'
import type { XtxLikeInstance } from '@/components/components'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotRecommend from './components/HotRecommend.vue'
import Skeleton from './components/Skeleton.vue'
import { queryHomeBanner, queryCategory, queryRecommend } from '@/services/home'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getBannerData = async () => {
  const res = await queryHomeBanner()
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getCategory = async () => {
  const res = await queryCategory()
  categoryList.value = res.result
}

// 获取热门推荐数据
const recommendList = ref<RecommendItem[]>([])
const getRecommend = async () => {
  const res = await queryRecommend()
  recommendList.value = res.result
}

// 猜你喜欢组件实例
const likeInstance = ref<XtxLikeInstance>()
// 滑动触底
const onScrolltolower = () => {
  likeInstance.value?.getMore()
}

// 当前下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新加载数据
const onRefresherrefresh = async () => {
  // 开启刷新动画
  isTriggered.value = true
  // 重置猜你喜欢数据
  likeInstance.value?.resetData()
  // 加载数据
  await Promise.all([getBannerData(), getCategory(), getRecommend(), likeInstance.value?.getMore()])
  // 结束刷新动画
  isTriggered.value = false
}

// 是否加载中标记
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBannerData(), getCategory(), getRecommend()])
  isLoading.value = false
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrolltolower"
    class="scroll-view"
    scroll-y
  >
    <!-- 骨架屏 -->
    <Skeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 前台分类 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐 -->
      <HotRecommend :list="recommendList" />
      <!-- 猜你喜欢 -->
      <XtxLike ref="likeInstance" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
  .scroll-view {
    flex: 1;
  }
}
</style>
